package com.rpp.study.service.impl;

import com.rpp.study.dao.LagouTokenRepository;
import com.rpp.study.dao.LagouUserRepository;
import com.rpp.study.entity.LagouToken;
import com.rpp.study.entity.LagouUser;
import com.rpp.study.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Description
 * @Author rpp
 * @Date 2020/8/28 11:19 下午
 */
@Slf4j
@Service
public class UserService implements IUserService {

    @Autowired
    LagouUserRepository userRepository;
    @Autowired
    LagouTokenRepository tokenRepository;

    /**
     * 注册接⼝，true成功，false失败
     *
     * @param email
     * @param password
     * @param code
     * @return
     */
    @Override
    public Boolean register(String email, String password, String code) {

        LagouUser lagouUser = userRepository.findByEmail(email);
        if (null != lagouUser) {
            log.info("对应用户不存在,email:{}", email);
            return false;
        }
        lagouUser = new LagouUser();
        lagouUser.setEmail(email);
        lagouUser.setPassword(password);
        lagouUser.setCreateTime(new Date());
        lagouUser.setUpdateTime(new Date());
        userRepository.save(lagouUser);
        log.info("用户注册成功,email:{}", email);
        return true;
    }

    /**
     * 是否已注册，根据邮箱判断,true代表已经注册过， false代表尚未注册
     *
     * @param email
     * @return
     */
    @Override
    public Boolean isRegistered(String email) {
        LagouUser lagouUser = userRepository.findByEmail(email);
        return lagouUser != null;
    }

    /**
     * 登录接⼝，验证⽤户名密码合法性，根据⽤户名和 密码生成token，token存入数据库，并写入cookie 中
     * 登录成功返回邮箱地址，重定向到欢迎⻚
     *
     * @param email
     * @param password
     * @return
     */
    @Override
    public Boolean login(String email, String password) {
        LagouUser lagouUser = userRepository.findByEmailAndPassword(email, password);
        return lagouUser != null;
    }

    /**
     * 根据token查询⽤户登录邮箱接⼝
     *
     * @param token
     * @return
     */
    @Override
    public String info(String token) {
        LagouToken lagouToken = tokenRepository.findByToken(token);
        return lagouToken.getEmail();
    }

    /**
     * 缓存token信息
     *
     * @param email
     * @param token
     */
    @Override
    public void saveOrUpdateToken(String email, String token) {
        LagouToken lagouToken = tokenRepository.findByEmailAndToken(email, token);
        if (null == lagouToken) {
            lagouToken = new LagouToken();
            lagouToken.setEmail(email);
            lagouToken.setToken(token);
        } else {
            lagouToken.setToken(token);
        }
        tokenRepository.save(lagouToken);
    }
}
